<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/24
 * Time: 10:49
 */

namespace app\api\model;


use constant\config;
use think\Model;
use think\Cache;
use think\Request;
use unionpay\AppUtil;

class PayModel extends Model
{
    /*
     * VSP501   微信支付
        VSP502  微信支付撤销
        VSP503  微信支付退款
        VSP505  手机QQ 支付
        VSP506  手机QQ支付撤销
        VSP507  手机QQ支付退款
        VSP511  支付宝支付
        VSP512  支付宝支付撤销
        VSP513  支付宝支付退款
        VSP541  扫码支付
        VSP542  扫码撤销
        VSP543  扫码退货
        VSP551  银联扫码支付
        VSP552  银联扫码撤销
        VSP553  银联扫码退货
        VSP907  差错借记调整
        VSP908  差错贷记调整
     */
    const cusid='55265108912SBJ2';//商户号  必填
    const appid='00214755';//应用ID  必填
    const version='11';//版本号
    const orgid='';//集团商户号
    const trxamt='';//交易金额单位为分  必填
    const reqsn='';//商户交易单号 必填
    const paytype='W06';//交易方式 必填
    const charset='UTF-8';//交易方式 必填
    const body='';//订单标题
    const remark='';//备注
    const validtime='30';//有效时间
    const acct='';//支付平台用户标识
    const notify_url='';//交易结果通知地址 必填
    const limit_pay='';//limit_pay
    const sub_appid='';//微信子appid
    const subbranch='';//门店号
    const cusip='';//终端ip
    const idno='';//证件号  实名交易必填.填了此字段就会验证证件号和姓名
    const truename='';//付款人真实姓名
    const fqnum='';//花呗分期6-花呗分期6期 12-花呗分期12期
    const randomstr='';
    const signtype='';//签名方式
    const front_url='';//支付完成后,交易成功后点击跳往商户网站,会跳往交易上送的front_url
    const APPID='00000003';
    const CUSID='990440148166000';
    const APIURL="https://vsp.allinpay.com/apiweb/unitorder/pay";//生产环境小程序

    const H5="https://syb.allinpay.com/apiweb/h5unionpay/unionorder";//开发环境H5

    const APIVERSION='11';

    //统一支付接口
    public function pay($data=[])
    {
        $new                 =new AppUtil();
        $params['cusid']     =$data['cusid'];
        $params['appid']     =$data['APP_ID'];
        $params['version']   =self::version;
        $params['charset']   =self::charset;
         $params['notify_url']='https://api-shopowner.yiniao.co/api/Callback/cash?city=' . config('city');
//        $params['notify_url']='https://weixiu.yiniaoweb.com/' . config('city') . '/api/Callback/cash';
        $params['body']      =$data['title'];
        $params['trxamt']    =$data['money']* 100;
        $params['reqsn']     =$this->OddNumbers();
        $params['returl']    ='https://www.91yiniao.com/';
        $params['key']       =$data['key'];
        $params['signtype']  ='';
        $params['randomstr'] ='randomstr';
        $params['validtime'] =self::validtime;
        $params["sign"]      =$new::Sign($params);//签名
        unset($params['key']);

        $paramsStr=$new::ToUrlParams1($params);
        $url      =self::H5;


        $this->request($url . '?' . $paramsStr, []);
        db('recharge')->insertGetId([
            'customers_id'=>0,
            'order_nos'   =>$params['reqsn'],
            'order_no'    =>$data['order_no'],
            'money'       =>$data['money'],
            'status'      =>0,
            'created_time'=>time(),
            'type'        =>2,
            'youhui_id'   =>0,
            'mode'        =>4,
            'project'     =>$data['project'],
            'pay_type'    =>1,
        ]);
        return $this->UserImg($params['reqsn'], $url . '?' . $paramsStr);


    }


    //统一被扫接口
    public function scanqrpay()
    {
        $params=[];

        $params["sign"]=AppUtil::Sign($params);//签名
        $paramsStr     =AppUtil::ToUrlParams($params);
        $url           =self::APIURL . "/scanqrpay";
        $rsp           =$this->request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray=json_decode($rsp, true);
        if ($this->validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }

    }


    //当天交易用撤销
    public function cancel()
    {
        $params=[];

        $params["sign"]=AppUtil::Sign($params);//签名
        $paramsStr     =AppUtil::ToUrlParams($params);
        $url           =self::APIURL . "/cancel";
        $rsp           =$this->request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray=json_decode($rsp, true);
        if ($this->validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

    //当天交易请用撤销,非当天交易才用此退货接口
    public function refund()
    {
        $params=[];

        $params["sign"]=AppUtil::Sign($params);//签名
        $paramsStr     =AppUtil::ToUrlParams($params);
        $url           =self::APIURL . "/refund";
        $rsp           =$this->request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray=json_decode($rsp, true);
        if ($this->validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

    public function query()
    {
        $params=[];

        $params["sign"]=AppUtil::Sign($params);//签名
        $paramsStr     =AppUtil::ToUrlParams($params);
        $url           =self::APIURL . "/query";
        $rsp           =$this->request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray=json_decode($rsp, true);
        if ($this->validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

    //发送请求操作仅供参考,不为最佳实践
    function request($url, $params)
    {
        $ch         =curl_init();
        $this_header=["content-type: application/x-www-form-urlencoded;charset=UTF-8"];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output=curl_exec($ch);
         curl_close($ch);
        return $output;
    }

    //验签
    function validSign($array)
    {
        if ("SUCCESS" == $array["retcode"]) {
            $signRsp      =strtolower($array["sign"]);
            $array["sign"]="";
            $sign         =strtolower(AppUtil::Sign($array));
            if ($sign == $signRsp) {
                return TRUE;
            } else{
                echo "验签失败:" . $signRsp . "--" . $sign;
            }
        } else{
            echo $array["retmsg"];
        }

        return FALSE;
    }

    public function UserImg($trxamt, $url)
    {
        vendor('phpqrcode.phpqrcode');//引入类库

        $value               =$url;         //二维码内容
        $errorCorrectionLevel='L';  //容错级别
        $matrixPointSize     =5;      //生成图片大小
        //生成二维码图片
        // 判断是否有这个文件夹  没有的话就创建一个
        if (!is_dir("qrcode")) {
            // 创建文件加
            mkdir("qrcode");
        }
        //设置二维码文件名
        $filename='qrcode/' . $trxamt . '.png';
        //生成二维码
        \QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);


    //如果需要转换成base64数据，解开下面这行注释即可
        $image_data = chunk_split(base64_encode(fread(fopen($filename, 'r'), filesize($filename))));
        // $request=Request::instance();
        // $domain =$request->domain();


        return $image_data;
    }
    
    

    public function OddNumbers()
    {
        $osn=date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return config('city') . $osn;
    }


}
